package com.goodcol.plugin.actions;

import com.goodcol.plugin.entity.TableInfo;
import com.goodcol.plugin.service.CodeGenerateService;
import com.goodcol.plugin.service.SettingsStorageService;
import com.goodcol.plugin.service.TableInfoSettingsService;
import com.goodcol.plugin.tool.CacheDataUtils;
import com.goodcol.plugin.tool.TypeMapperUtils;
import com.goodcol.plugin.ui.ConfigTableDialog;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 表配置菜单
 *
 * @author QuickCode
 * @version 1.0.0
 */
public class ConfigTableAction extends AnAction {

    /**
     * 处理方法
     *
     * @param event 事件对象
     */
    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        Project project = event.getProject();
        if (project == null) {
            return;
        }
        // 处理选中的表
        if(!CodeGenerateService.getInstance(project).cacheSelectedTables(event)) {
            return;
        }
        // 校验类型映射
        if (!TypeMapperUtils.processTypeValidator(project, CacheDataUtils.getInstance().getDbTableList())) {
            // 没通过不打开窗口
            return;
        }
        // 选中的表
        List<TableInfo> selectedTables = CacheDataUtils.getInstance().getDbTableList().stream()
                .map(dbTable -> TableInfoSettingsService.getInstance().getTableInfo(dbTable,
                        SettingsStorageService.getSettingsStorage().getCurrTemplateGroupName())).collect(Collectors.toList());
        if (!selectedTables.isEmpty()) {
            new ConfigTableDialog(project, selectedTables).show();
        }
    }
}
